import logging
from logging.handlers import RotatingFileHandler
import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager

from config import Config


app = Flask(__name__)

# 管理登录的扩展
login = LoginManager(app)
login.login_view = 'login' # 登录拦截器

# 使application读取配置文件
app.config.from_object(Config)


'''
缺一个发送错误日志到电子邮件
'''
'''
将日志保存到logs文件夹下
'''
if not app.debug:

    if not os.path.exists('logs'):
        os.mkdir('logs')
    # 设置日志文件最大为10kb，并且将最近的10个日子好备份
    file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240,
                                       backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)

    app.logger.setLevel(logging.INFO)
    app.logger.info('Microblog startup')

db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app import routes, models, errors